<div>
    <div class="input-group">
        <div class="form-control" type="text">
            <span class="default-text {{ $address ? 'd-none' : '' }}" style="opacity:0.75">选择地址</span>
            <span class="option {{ $address ? '' : 'd-none' }}">{{ $address }}</span>
            <input id="location_input" type="hidden" name="{{ $name }}" value="{{ $address }}">
            <input id="lon" type="hidden" name="longitude" value="{{ $longitude }}">
            <input id="lat" type="hidden" name="latitude" value="{{ $latitude }}">
        </div>
        <div class="input-group-append">
            <span id="open_map_btn">
                <span style="cursor: pointer" class="switch-dialog">
                    <div class="btn btn-primary">
                        &nbsp;<i class="feather icon-arrow-up"></i>&nbsp;
                    </div>
                </span>
            </span>
        </div>
    </div>
    <!-- 弹窗 -->
    <div class="modal fade" id="map_modal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" style="max-width:900px;">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">地图选址</h5>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body d-flex" style="height:500px;">
                    <div style="flex:2; padding-right:10px; display:flex; flex-direction: column;">
                        <input type="text" id="map_search" class="form-control mb-2" placeholder="输入地址搜索">
                        <div id="map_container" style="flex:1; border:1px solid #ddd;"></div>
                    </div>
                    <div id="search_results" style="flex:1; border-left:1px solid #ddd; padding-left:10px; overflow-y:auto;">
                        <!-- 搜索结果 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" id="confirm_btn" class="btn btn-primary">确认选择</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    window._AMapSecurityConfig = {
        securityJsCode: "65fa7eca824723217810a0415ec72302",
    };
</script>
<script src="https://webapi.amap.com/maps?v=2.0&key=46d25b98e7e627c68941e7a2aee10f5e"></script>

<script>
    (function(){
        let map, marker, autoComplete, placeSearch;
        let selectedPos = null;

        function initMap() {
            map = new AMap.Map('map_container', {
                viewMode: "2D", //默认使用 2D 模式
                zoom: 13,
                center: [116.397428, 39.90923]
            });

            marker = new AMap.Marker({ map: map });

            // v2版本插件异步加载方式
            AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], function() {
                autocomplete = new AMap.AutoComplete({
                    input: 'map_search'
                });

                placeSearch = new AMap.PlaceSearch({
                    map: map,
                    pageSize: 5,
                    panel: 'search_results',
                    autoFitView: true
                });
            });
        }

        function clearResults() {
            document.getElementById('search_results').innerHTML = '';
        }

        document.getElementById('open_map_btn').addEventListener('click', function(){
            $('#map_modal').modal('show');
            if (!map) {
                initMap();
            }
            setTimeout(() => {
                if (map && typeof map.resize === 'function') {
                    map.resize();
                }
            }, 200);
        });

        document.getElementById('map_search').addEventListener('input', function(){
            let val = this.value.trim();
            let resultsDiv = document.getElementById('search_results');
            if (!val) {
                resultsDiv.innerHTML = '';
                return;
            }
            if (!placeSearch) {
                resultsDiv.innerHTML = '<p>加载中，请稍候...</p>';
                return;
            }
            placeSearch.search(val, function(status, result){
                if(status !== 'complete' || !result.poiList) {
                    resultsDiv.innerHTML = '<p>无结果</p>';
                    return;
                }
                let pois = result.poiList.pois;
                let html = '';
                pois.forEach(poi => {
                    html += `<div class="search-item" data-lng="${poi.location.lng}" data-lat="${poi.location.lat}" style="padding:5px; cursor:pointer; border-bottom:1px solid #eee;">
                    <b>${poi.name}</b><br><small>${poi.address}</small>
                </div>`;
                });
                resultsDiv.innerHTML = html;

                resultsDiv.querySelectorAll('.search-item').forEach(item => {
                    item.addEventListener('click', function(){
                        let lng = parseFloat(this.dataset.lng);
                        let lat = parseFloat(this.dataset.lat);
                        let name = this.querySelector('b').innerText;
                        map.setCenter([lng, lat]);
                        marker.setPosition([lng, lat]);
                        selectedPos = new AMap.LngLat(lng, lat);
                        updateInput(name);
                        clearResults();

                    });
                });
            });
        });

        function updateInput(name) {
            if (selectedPos) {
                document.getElementById('lon').value = selectedPos.lng
                document.getElementById('lat').value = selectedPos.lat
                document.getElementById('map_search').value = name;
                document.getElementById('location_input').value = name;
                let option = document.querySelector('.option')
                let default_text = document.querySelector('.default-text')
                option.classList.remove('d-none');
                default_text.classList.add('d-none');
                option.innerHTML = name;
            }
        }

        document.getElementById('confirm_btn').addEventListener('click', function(){
            $('#map_modal').modal('hide');
        });
    })();
</script>
